import java.util.*;

/**
 * @Author 12629
 * @Description：
 */
public class BinaryTree {

    static class TreeNode {
        public char val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(char val) {
            this.val = val;
        }
    }
    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');
        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        //E.right = H;
        return A;
    }

    /*public static int i = 0;
    public static TreeNode createTree(String str) {
        TreeNode root = null;
        if(str.charAt(i) != '#') {
            root = new TreeNode(str.charAt(i));
            i++;
            root.left = createTree(str);
            root.right = createTree(str);
        }else {
            i++;
        }
        return root;
    }*/

      // 前序遍历
    public void preOrder(TreeNode root) {
        if(root == null) return;
        System.out.print(root.val+" ");
        preOrder(root.left);
        preOrder(root.right);
    }

    // 中序遍历
    public void inOrder(TreeNode root) {
        if(root == null) return;
        inOrder(root.left);
        System.out.print(root.val+" ");
        inOrder(root.right);
    }

    // 后序遍历
    public void postOrder(TreeNode root) {
        if(root == null) return;
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val+" ");
    }


    public int nodeSize;
    /**
     * 遍历思路
     * 获取当前二叉树的节点个数
     * @param root
     * @return
     */
    public void getNodeSize(TreeNode root) {
        if(root == null) return ;
        nodeSize++;
        getNodeSize(root.left);
        getNodeSize(root.right);
    }

    public int getNodeSize2(TreeNode root) {
        if(root == null) return 0;
        return getNodeSize2(root.left) +
                getNodeSize2(root.right) + 1;
    }

    public int leafCount;
    /**
     * 获取叶子节点的个数 - 遍历思路
     * @param root
     */
    public void getLeafNodeCount(TreeNode root) {
        if(root == null) {
            return;
        }
        if(root.left == null && root.right == null) {
            leafCount++;
        }
        getLeafNodeCount(root.left);
        getLeafNodeCount(root.right);
    }

    /**
     * 获取叶子节点的个数  - 子问题
     * @param root
     * @return
     */
    public int getLeafNodeCount2(TreeNode root) {
        if(root == null) {
            return 0;
        }
        if(root.left == null && root.right == null) {
            return 1;
        }
        return getLeafNodeCount2(root.left) +
                getLeafNodeCount2(root.right);
    }

    /**
     * 第K层节点的个数
     * @param root
     * @param k
     * @return
     */
    public int getKLevelNodeCount(TreeNode root,int k) {
        if(root == null) {
            return 0;
        }
        if(k == 1) {
            return 1;
        }
        return getKLevelNodeCount(root.left,k-1) +
                getKLevelNodeCount(root.right,k-1);
    }

    /**
     * 二叉树的高度
     * 时间复杂度：O(N)
     * @param root
     * @return
     */
    public int getHeight(TreeNode root) {
        if(root == null) return 0;
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);

        return Math.max(leftHeight,rightHeight) + 1;

        //return leftHeight > rightHeight ? leftHeight+1 : rightHeight+1;
        //return getHeight(root.left) > getHeight(root.right) ?
                //getHeight(root.left)+1 : getHeight(root.right)+1;
    }

    public TreeNode find(TreeNode root,char key) {
        if(root == null) {
            return null;
        }
        if(root.val == key) {
            return root;
        }
        TreeNode leftResult = find(root.left,key);
        if(leftResult != null) {
            return leftResult;
        }

        TreeNode rightResult = find(root.right,key);
        if(rightResult != null) {
            return rightResult;
        }

        return null;
    }

    // p -> m    q -> n  时间复杂度：O(min(m,n))
    public boolean isSameTree(TreeNode p, TreeNode q) {
        //1. 一个为空 一个不为空 【结构上】
        if( (p == null && q != null) || (p != null && q == null)) {
            return false;
        }
        //2. 此时 都不为空  或者 都为空 才能走到这里
        if(p == null && q == null ) {
            return true;
        }

        if(p.val != q.val) {
            return false;
        }
        //3. 此时代码走到这里  代表：p != null && q != null  && p.val == q.val
        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }

    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if(root == null)return false;
        if(isSameTree(root,subRoot)) return true;
        if(isSubtree(root.left,subRoot))return true;
        if(isSubtree(root.right,subRoot))return true;
        return false;
    }

    public TreeNode invertTree(TreeNode root) {
        if(root == null) return null;
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;

        invertTree(root.left);
        invertTree(root.right);
        return root;
    }


    public boolean isBalanced(TreeNode root) {
        if(root == null) return true;

        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);

        return Math.abs(leftHeight - rightHeight) <= 1
                && isBalanced(root.left) && isBalanced(root.right);

    }


    public boolean isBalanced2(TreeNode root) {
        if(root == null) return true;
        return maxDepth(root) >= 0;
    }

    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        int leftHeight = maxDepth(root.left);
        if(leftHeight < 0) {
            return -1;
        }
        int rightHeight = maxDepth(root.right);
        if(leftHeight >= 0 &&  rightHeight >= 0 &&
                Math.abs(leftHeight - rightHeight) <= 1) {
            return Math.max(leftHeight,rightHeight) + 1;
        }else {
            return -1;
        }
    }

    public boolean isSymmetric(TreeNode root) {
        if(root == null) return true;
        return isSymmetricChile(root.left,root.right);
    }

    public boolean isSymmetricChile(TreeNode leftTree,TreeNode rightTree) {
        if(leftTree == null && rightTree != null ||
                leftTree != null && rightTree == null) {
            return false;
        }
        if(leftTree == null && rightTree == null ) {
            return true;
        }
        if(leftTree.val != rightTree.val) {
            return false;
        }
        return isSymmetricChile(leftTree.left,rightTree.right)
                && isSymmetricChile(leftTree.right,rightTree.left);
    }

    public void levelOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.print(cur.val+" ");
            if(cur.left != null) {
                queue.offer(cur.left);
            }
            if(cur.right != null) {
                queue.offer(cur.right);
            }
        }
    }


   /* public List<List<Integer>> levelOrder2(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> tmpList= new ArrayList<>();
            int size = queue.size();
            while (size != 0) {
                TreeNode cur = queue.poll();
                size--;
                //System.out.print(cur.val+" ");
                tmpList.add(cur.val);
                if(cur.left != null) {
                    queue.offer(cur.left);
                }
                if(cur.right != null) {
                    queue.offer(cur.right);
                }

            }
            ret.add(tmpList);
        }
        return ret;
    }*/

    public boolean isCompleteTree(TreeNode root) {
        if(root == null) return true;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if(cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            }else {
                break;
            }
        }
        while (!queue.isEmpty()) {
            TreeNode cur = queue.peek();
            if(cur == null) {
                queue.poll();
            }else {
                return false;
            }
        }
        return true;
    }

    public TreeNode lowestCommonAncestor(TreeNode root,
                                         TreeNode p, TreeNode q) {
        if(root == null) {
            return root;
        }
        if(root == p || root == q) {
            return root;
        }
        TreeNode leftTree = lowestCommonAncestor(root.left,p,q);
        TreeNode rightTree = lowestCommonAncestor(root.right,p,q);
        if(leftTree != null && rightTree != null) {
            return root;
        }else if(leftTree != null) {
            return leftTree;
        }else {
            return rightTree;
        }
    }

    public TreeNode lowestCommonAncestor2(TreeNode root,
                                         TreeNode p, TreeNode q) {
        Stack<TreeNode> stackP = new Stack<>();
        Stack<TreeNode> stackQ = new Stack<>();
        getPath(root,p,stackP);
        getPath(root,q,stackQ);

        int sizeP = stackP.size();
        int sizeQ = stackQ.size();
        if(sizeP > sizeQ) {
            int size = sizeP - sizeQ;
            while (size != 0) {
                stackP.pop();
                size--;
            }
        }else {
            int size = sizeQ - sizeP;
            while (size != 0) {
                stackQ.pop();
                size--;
            }
        }

        while (!stackP.isEmpty() && !stackQ.isEmpty()) {
            TreeNode val1 = stackP.pop();
            TreeNode val2 = stackQ.pop();
            if(val1 == val2) {
                return val1;
            }
        }
        return null;
    }

    private boolean getPath(TreeNode root, TreeNode node,
                            Stack<TreeNode> stack) {
        if(root == null) {
            return false;
        }
        stack.push(root);
        if(root == node) {
            return true;
        }
        boolean flg = getPath(root.left,node,stack);
        if(flg) {
            return true;
        }
        flg = getPath(root.right,node,stack);
        if(flg) {
            return true;
        }
        stack.pop();
        return false;
    }

    /*
    class Solution {

    public int preIndex = 0;
    public TreeNode buildTree(int[] preorder, int[] inorder) {

        return buildTreeChilde(preorder,inorder,0,inorder.length-1);
    }

    public TreeNode buildTreeChilde(int[] preorder, int[] inorder,int inbegin,int inend) {

        if(inbegin > inend) {
            return null;
        }

        TreeNode root = new TreeNode(preorder[preIndex]);

        int rootIndex = findVal(inorder,inbegin,inend,preorder[preIndex]);
        preIndex++;

        root.left = buildTreeChilde(preorder,inorder,inbegin,rootIndex-1);

        root.right = buildTreeChilde(preorder,inorder,rootIndex+1,inend);

        return root;
    }

    private int findVal(int[] inorder,int inbegin,int inend,int key) {
        for(int i = inbegin; i<= inend;i++) {
            if(inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }
}
     */



    /*
    class Solution {

    public int postIndex = 0;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        postIndex = postorder.length-1;

        return buildTreeChilde(postorder,inorder,0,inorder.length-1);
    }

    public TreeNode buildTreeChilde(int[] postorder, int[] inorder,int inbegin,int inend) {

        if(inbegin > inend) {
            return null;
        }

        TreeNode root = new TreeNode(postorder[postIndex]);

        int rootIndex = findVal(inorder,inbegin,inend,postorder[postIndex]);
        postIndex--;


        root.right = buildTreeChilde(postorder,inorder,rootIndex+1,inend);

        root.left = buildTreeChilde(postorder,inorder,inbegin,rootIndex-1);


        return root;
    }

    private int findVal(int[] inorder,int inbegin,int inend,int key) {
        for(int i = inbegin; i<= inend;i++) {
            if(inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }
}
     */

    public String tree2str(TreeNode root) {
        StringBuilder stringBuilder = new StringBuilder();
        tree2strChild(root,stringBuilder);
        return stringBuilder.toString();
    }

    public void tree2strChild(TreeNode root,StringBuilder stringBuilder) {
        if(root == null) return;
        stringBuilder.append(root.val);
        //左子树
        if(root.left != null) {
            stringBuilder.append("(");
            tree2strChild(root.left,stringBuilder);
            stringBuilder.append(")");
        }else {
            if(root.right == null) {
                return;
            }else {
                stringBuilder.append("()");
            }
        }
        //右子树
        if(root.right != null) {
            stringBuilder.append("(");
            tree2strChild(root.right,stringBuilder);
            stringBuilder.append(")");
        }else {
            return;
        }
    }

    public List<Character> preorderTraversal(TreeNode root) {
        List<Character> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                System.out.print(cur.val + " ");
                ret.add(cur.val);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
        return ret;
    }

    public List<Character> inorderTraversal(TreeNode root) {
        List<Character> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            System.out.print(top.val + " ");
            ret.add(top.val);
            cur = top.right;
        }
        return ret;
    }

   /* public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();
            if(top.right == null || top.right == prev) {
                stack.pop();
                ret.add(top.val);
                prev = top;
            }else {
                cur = top.right;
            }
        }
        return ret;
    }*/
}
